package org.grayrabbit.cms.util;

import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import org.grayrabbit.cms.constant.UsercenterStaticValues;
import org.grayrabbit.cms.entity.User;


public class UserSessionContext {
	
	private static Map<String, Map<String,HttpSession>> userPool = new Hashtable<String , Map<String, HttpSession>>();
	private static Map<String, HttpSession> sessionPool = new Hashtable<String, HttpSession>();
	private static User user;
	
	public static Map<String,HttpSession> getUserPool(String userId){
		return userPool.get(userId);
	}
	/**
	 * 登录
	 * @param se
	 */
	public static void put(HttpSessionEvent se){
		user = getCurrentUser(se);
		if(null != user) {
			if(!sessionPool.containsKey(se.getSession().getId())) {
				sessionPool.put(se.getSession().getId(), se.getSession());
				userPool.put(user.getUserId(), sessionPool);
			}
		}
	}
	/**
	 * 强制下线
	 * @param userId
	 */
	public static void remove(String userId){
		if(null != userPool.get(userId)) {
			userPool.remove(userId);
		}
	}
	/**
	 * 自动退出
	 * @param se
	 */
	public static void remove(HttpSessionEvent se){
		user = getCurrentUser(se);
		if(null != user) {
			sessionPool.remove(se.getSession().getId());
			if(sessionPool.isEmpty()) {
				userPool.remove(user.getUserId());
			}
		}
	}
	
	private static User getCurrentUser(HttpSessionEvent se) {
		return (User)se.getSession().getAttribute(UsercenterStaticValues.CURRENT_MEMBER);
	}

}
